# -*- coding: utf-8 -*-
"""
@author: hunan
@date: 2024-12-08
@description: 
"""
import logging
import socket
import traceback

import nltk
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

from product_upload.util.basic.common_util import check_and_kill_port
from product_upload.util.basic.scheduled import scheduler
from product_upload.util.seller import amazon_us_util
from product_upload.util.seller.amazon_us_util import old_initialize_redis_from_files
from product_upload.web.router import router

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(module)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)

app = FastAPI()

app.include_router(router)


@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    print(f"Request {request.url} raised an exception: {exc}")
    print(traceback.format_exc())  # 打印详细错误
    return JSONResponse(status_code=500, content={"message": "Internal server error, please try again later."})


def init():
    nltk.download('words')
    nltk.download('wordnet')
    nltk.download('omw-1.4')


if __name__ == "__main__":
    PORT = 8848
    WORKERS = 1
    init()
    if socket.gethostname().lower() == "admin_pro":
        old_initialize_redis_from_files()
    check_and_kill_port(PORT)
    logging.info(f"Starting server on port {PORT} with {WORKERS} workers...")
    scheduler.start()
    logging.info("Scheduler started...")
    uvicorn.run("start:app", host="0.0.0.0", port=PORT, workers=WORKERS, reload=False)
